﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AliyunOSServiceLib.Services;
using Ceremony.API.Application.Queries;
using Ceremony.API.Model;
using Ceremony.API.ParameterModel;
using Ceremony.API.ViewModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Ceremony.API.Controllers
{
    [Route("api/v1/ceremony")]
    [ApiController]
    public class WechatMomentController : ControllerBase
    {
        private readonly ILogger<WechatMomentController> _logger;
        private readonly CeremonyContext _context;
        private readonly ICeremonyQueries _queries;
        private readonly IAliyunOSService _aliyunOSService;
        private readonly CeremonySettings _settings;
        public WechatMomentController(ILogger<WechatMomentController> logger, 
            CeremonyContext context, 
            ICeremonyQueries queries,
            IAliyunOSService aliyunOSService,
            IOptionsSnapshot<CeremonySettings> settings)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _queries = queries ?? throw new ArgumentNullException(nameof(queries));
            _aliyunOSService = aliyunOSService ?? throw new ArgumentNullException(nameof(aliyunOSService));
            _settings = settings.Value ?? throw new ArgumentNullException(nameof(settings));
        }
        /// <summary>
        /// 创建朋友圈
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [Route("wechatmoment")]
        [HttpPost]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> CreateWechatMomentAsync([FromBody]WechatMomentParameter parameter)
        {
            var wechatMoment = new WechatMoment(parameter.OverheadOrder, parameter.UserId, parameter.Message, parameter.ImageNames);
            await _context.AddAsync(wechatMoment);
            var result = await _context.SaveChangesAsync();
            string resultStr = result > 0 ? "succeed" : "failed";
            _logger.LogInformation("----- Create WechatMoment {Result}:- {IdProperty}: {WechatMomentId} ({@WechatMoment})",
                resultStr,
                nameof(wechatMoment.Id),
                wechatMoment.Id,
                wechatMoment);
            if (result > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(500, "创建朋友圈失败");
            }
        }
        /// <summary>
        /// 删除朋友圈
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("wechatmoment/{id:int}")]
        [HttpDelete]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> DeleteWechatMomentAsync(int id)
        {
            var wechatMoment = await _context.WechatMoments.FindAsync(id);
            if(wechatMoment == null)
            {
                return NotFound();
            }
            else
            {
                wechatMoment.Remove();
                _context.WechatMoments.Update(wechatMoment);
                var result = await _context.SaveChangesAsync();
                string resultStr = result > 0 ? "succeed" : "failed";
                _logger.LogInformation("----- Delete WechatMoment {Result}:- {IdProperty}: {WechatMomentId} ({@WechatMoment})",
                    resultStr,
                    nameof(wechatMoment.Id),
                    wechatMoment.Id,
                    wechatMoment);
                if (result > 0)
                {
                    return Ok();
                }
                else
                {
                    return StatusCode(500, "创建朋友圈失败");
                }
            }
        }
        /// <summary>
        /// 获取朋友圈
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[Route("wechatmoments")]
        //[HttpPost]
        //[ProducesResponseType(typeof(WechatMomentSummaryViewModel),(int)HttpStatusCode.OK)]
        //[ProducesResponseType((int)HttpStatusCode.BadRequest)]
        //public async Task<ActionResult<WechatMomentSummaryViewModel>> GetWechatMomentsAsync([FromBody]BaseFilter filter)
        //{
        //    var wechatMoment = await _queries.GetWechatMomentsAsync(filter);
        //    if(wechatMoment.WechatMoments != null)
        //    {
        //        DateTime dt = DateTime.Now;
        //        foreach (var item in wechatMoment.WechatMoments)
        //        {
        //            TimeSpan ts = dt - item.CreateTime;
        //            if (ts.TotalMinutes <= 30)
        //                item.FormatCreateTime = "刚刚";
        //            else if (ts.TotalMinutes <= 60)
        //                item.FormatCreateTime = string.Format("{0}分钟前", Convert.ToInt32(ts.TotalMinutes));
        //            else if (ts.TotalMinutes <= 60 * 24)
        //                item.FormatCreateTime = string.Format("{0}小时前", Convert.ToInt32(ts.TotalMinutes / 60));
        //            else if (ts.TotalMinutes <= 60 * 24 * 2)
        //                item.FormatCreateTime = "1天前";
        //            else
        //                item.FormatCreateTime = item.CreateTime.ToString("M月d日HH时mm分");
        //            item.ImageUrls = GetPicUrl(_settings.WechatMomentImagePath, item.ImageNames);
        //        }
        //    }
        //    return Ok(wechatMoment);
        //}
        [Route("wechatmoments")]
        [HttpPost]
        [ProducesResponseType(typeof(WechatMomentSummaryViewModel), (int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<ActionResult<WechatMomentSummaryViewModel>> GetWechatMomentsAsync([FromBody]WechatMomentFilter filter)
        {
            var wechatMoment = await _queries.GetWechatMomentsPagingAsync(filter);
            if (wechatMoment.WechatMoments != null)
            {
                DateTime dt = DateTime.Now;
                foreach (var item in wechatMoment.WechatMoments)
                {
                    TimeSpan ts = dt - Convert.ToDateTime(item.CreateTime);
                    if (ts.TotalMinutes <= 30)
                        item.FormatCreateTime = "刚刚";
                    else if (ts.TotalMinutes <= 60)
                        item.FormatCreateTime = string.Format("{0}分钟前", Convert.ToInt32(ts.TotalMinutes));
                    else if (ts.TotalMinutes <= 60 * 24)
                        item.FormatCreateTime = string.Format("{0}小时前", Convert.ToInt32(ts.TotalMinutes / 60));
                    else if (ts.TotalMinutes <= 60 * 24 * 2)
                        item.FormatCreateTime = "1天前";
                    else
                        item.FormatCreateTime = Convert.ToDateTime(item.CreateTime).ToString("M月d日HH时mm分");
                    item.ImageUrls = GetPicUrl(_settings.WechatMomentImagePath, item.ImageNames);
                }
            }
            return Ok(wechatMoment);
        }
        /// <summary>
        /// 创建评论
        /// </summary>
        /// <param name="comment"></param>
        /// <returns></returns>
        [Route("comment")]
        [HttpPost]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> CreateCommentAsync([FromBody]CreateComment comment)
        {
            var commentModel = new Comment(comment.WechatMomentId, comment.CommentType, Convert.ToInt32(comment.FromUserId), Convert.ToInt32(comment.ToUserId), comment.CommentMessage);
            await _context.Comments.AddAsync(commentModel);
            var result = await _context.SaveChangesAsync();
            string resultStr = result > 0 ? "succeed" : "failed";
            _logger.LogInformation("----- Create Comment {Result}:- {IdProperty}: {CommentId} ({@Comment})",
                resultStr,
                nameof(commentModel.Id),
                commentModel.Id,
                commentModel);
            if (result > 0)
            {
                return Ok(commentModel);
            }
            else
            {
                return StatusCode(500, "创建评论失败");
            }
        }
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("comment/{id:int}")]
        [HttpDelete]
        [ProducesResponseType((int)HttpStatusCode.OK)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> DeleteCommentAsync(int id)
        {
            var comment = await _context.Comments.FindAsync(id);
            if(comment == null)
            {
                return NotFound();
            }
            else
            {
                comment.Remove();
                _context.Comments.Update(comment);
                var result = await _context.SaveChangesAsync();
                string resultStr = result > 0 ? "succeed" : "failed";
                _logger.LogInformation("----- Delete Comment {Result}:- {IdProperty}: {CommentId} ({@Comment})",
                    resultStr,
                    nameof(comment.Id),
                    comment.Id,
                    comment);
                if (result > 0)
                {
                    return Ok();
                }
                else
                {
                    return StatusCode(500, "删除评论失败");
                }
            }
        }

        private List<FileUrl> GetPicUrl(string objectName, string picNames)
        {
            try
            {
                if (string.IsNullOrEmpty(picNames) || string.IsNullOrEmpty(objectName))
                    return null;
                List<FileUrl> files = new List<FileUrl>();
                string[] picArray = picNames.Trim(';').Split(';');
                for (int i = 0; i < picArray.Length; i++)
                {
                    string key = objectName + "/" + picArray[i];
                    string url = _aliyunOSService.GetGeneratePresignedUri(key);
                    files.Add(new FileUrl { Name = picArray[i], Url = url });
                }
                return files;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
            return null;
        }
    }
}